package com.ruoyi.system.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.reservationserver.dao.ReservationsDao;
import com.ruoyi.reservationserver.service.ReservationsService;
import com.ruoyi.reservationserver.service.StadiumStatisticService;
import com.ruoyi.reservationserver.utils.Result;
import com.ruoyi.system.domain.Court;
import com.ruoyi.system.domain.CourtStatistic;
import com.ruoyi.system.domain.StadiumStatistic;
import com.ruoyi.system.service.CourtStatisticService;
import com.ruoyi.system.service.ICourtService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Reservations;
import com.ruoyi.system.service.IReservationsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 预约信息管理Controller
 * 
 * @author guiye
 * @date 2023-08-27
 */
@RestController
@RequestMapping("/system/reservations")
public class ReservationsController extends BaseController
{
    @Autowired
    private ICourtService courtService;
    @Autowired
    private IReservationsService reservationsService;
    @Resource
    private ReservationsService reservationsService1;
    @Resource
    private ReservationsDao reservationsDao;

    @Resource
    private CourtStatisticService courtStatisticService;

    @Resource
    private StadiumStatisticService stadiumStatisticService;

    /**
     * 根据场地ID和预约日期，返回三个时间段的剩余容量（默认是最大容量）
     */
    @GetMapping("/remainCapacity")
    public AjaxResult remainCapacity(@RequestParam Long courtId, @RequestParam  String reservationDate){
        Court court = courtService.selectCourtByCourtId(courtId);
//        总体最大预约量
        String capacity = court.getCapacity();
        int intCapacity = Integer.parseInt(capacity);
//        初始化各时间段的值
        int morning = intCapacity, afternoon = intCapacity, evening = intCapacity;

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("court_id",courtId);
        queryWrapper.eq("reservation_date",reservationDate);
        List<Reservations> reservationsList = reservationsService.list(queryWrapper);
        System.out.println(reservationsList);
        for (Reservations reservations : reservationsList) {
            if (reservations.getReservationTimeSlot().equals("7:00~12:00")){
                morning-=reservations.getReservationNum();
                if (morning<0) {morning=0;}
            }else if (reservations.getReservationTimeSlot().equals("13:00~18:00")){
                afternoon-=reservations.getReservationNum();
                if (afternoon<0) {afternoon=0;}
            }else if (reservations.getReservationTimeSlot().equals("19:00~22:00")){
                evening-=reservations.getReservationNum();
                if (evening<0) {evening=0;}
            }else {
                return AjaxResult.error("时间段异常");
            }
        }
        ArrayList<Integer> list=new ArrayList<>();
        list.add(morning);
        list.add(afternoon);
        list.add(evening);
        return AjaxResult.success(list);

    }
    /**
     * 通过场地id获取场地名
     */



    /**
     * 查询预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:list')")
    @GetMapping("/list")
    public TableDataInfo list(Reservations reservations)
    {
        startPage();
        List<Reservations> list = reservationsService.selectReservationsList(reservations);

        return getDataTable(list);
    }

    /**
     * 导出预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:export')")
    @Log(title = "预约管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Reservations reservations)
    {
        List<Reservations> list = reservationsService.selectReservationsList(reservations);
        ExcelUtil<Reservations> util = new ExcelUtil<Reservations>(Reservations.class);
        util.exportExcel(response, list, "预约管理数据");
    }

    /**
     * 获取预约管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:query')")
    @GetMapping(value = "/{reservationId}")
    public AjaxResult getInfo(@PathVariable("reservationId") Long reservationId)
    {
        return success(reservationsService.selectReservationsByReservationId(reservationId));
    }

    /**
     * 新增预约管理
     */
//    @PreAuthorize("@ss.hasPermi('system:reservations:add')")
    @Log(title = "预约管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Reservations reservations)
    {
        QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stadium_id", 1);

        CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);
        System.out.println("新增的预约数："+reservations.getReservationNum()+",/当前的预约数："+courtStatistic.getReservationNum());
        courtStatistic.setReservationNum((int) (courtStatistic.getReservationNum()+reservations.getReservationNum()));
        courtStatisticService.update(courtStatistic);

        QueryWrapper<StadiumStatistic> wrapper = new QueryWrapper<>();
        wrapper.eq("stadium_statistic_id", 1);
        StadiumStatistic stadiumStatistic = stadiumStatisticService.getOne(wrapper);
        stadiumStatistic.setTotalReservationNum(courtStatistic.getReservationNum());
        stadiumStatisticService.update(stadiumStatistic);
        return toAjax(reservationsService.insertReservations(reservations));

    }

    /**
     * 修改预约管理
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:edit')")
    @Log(title = "预约管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Reservations reservations)
    {
        return toAjax(reservationsService.updateReservations(reservations));
    }

    /**
     * 删除预约管理
     */
    @PreAuthorize("@ss.hasPermi('system:reservations:remove')")
    @Log(title = "预约管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{reservationIds}")
    public AjaxResult remove(@PathVariable Long[] reservationIds)
    {
        for (int i = 0; i < reservationIds.length; i++) {
            Long id = reservationIds[i];
            Reservations reservations = reservationsService.selectReservationsByReservationId(id);
            QueryWrapper<CourtStatistic> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stadium_id", 1);
            CourtStatistic courtStatistic = courtStatisticService.getOne(queryWrapper);

            courtStatistic.setReservationNum((int) (courtStatistic.getReservationNum()-reservations.getReservationNum()));
            courtStatisticService.update(courtStatistic);

            QueryWrapper<StadiumStatistic> wrapper = new QueryWrapper<>();
            wrapper.eq("stadium_statistic_id", 1);
            StadiumStatistic stadiumStatistic = stadiumStatisticService.getOne(wrapper);
            stadiumStatistic.setTotalReservationNum((int) (stadiumStatistic.getTotalReservationNum()-reservations.getReservationNum()));
            stadiumStatisticService.update(stadiumStatistic);
        }
        return toAjax(reservationsService.deleteReservationsByReservationIds(reservationIds));
    }


    /**
     * 分页获取用户数据
     *
     * @param page
     * @param count
     * @return
     */
    @GetMapping
    public Result index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count) {
        PageInfo<com.ruoyi.reservationserver.entity.Reservations> pageInfo = reservationsService1.selectReservationWithPage(page, count);
        return Result.success(pageInfo);
    }

    /**
     * 通过场地名查询预约记录
     *
     * @param courtName
     * @return
     */
    @GetMapping("selectReservationsByCourtName")
    public Result selectUserByAccount(@RequestParam String courtName) {
        List<com.ruoyi.reservationserver.entity.Reservations> reservationsList;
        if (courtName == null) {
            return Result.error("不能输入空信息");
        }
        reservationsList=reservationsDao.selectReservationsByCourtName(courtName);
        return Result.success(reservationsList);
    }

    /**
     * 筛选出已取消的预约信息
     */
    @GetMapping("selectListWithQuXiao")
    public TableDataInfo selectListWithQuXiao(){
        QueryWrapper<Reservations> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("reservation_status",0);
        List<Reservations> reservationsList = reservationsService.list(queryWrapper);

        return getDataTable(reservationsList);
    }


}
